package com.dayu.gulimall.service.impl;

import com.alibaba.fastjson.JSON;
import com.dayu.common.to.es.SkuEsModel;
import com.dayu.gulimall.config.ElasticSearchConfig;
import com.dayu.gulimall.constant.EsConstant;
import com.dayu.gulimall.service.ElaticSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dayu
 * @version 1.0
 * @email dayu007@foxmail.com
 * @date 2020/12/6 20:50
 * @description
 */
@Slf4j
@Service
public class ElaticSaveServiceImpl implements ElaticSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 商品的上架
     *
     * @param esModelList
     * @return
     * @throws IOException
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> esModelList) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : esModelList) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.index(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架完成：{}", collect);
        return b;
    }
}
